//
//  ShopCarController.m
//  CenturyCity
//
//  Created by beisheng03 on 2017/11/21.
//  Copyright © 2017年 beisheng. All rights reserved.
//

#import "ShopCarController.h"
#import "ShopCarOHeaderView.h"
#import "ShopCarTHeaderView.h"
#import "ShopCarGoodsCell.h"
#import "ShopCarNothingCell.h"
#import "RecommendGoodsCell.h"
//#import "ShopCar.h"
//#import "GoodsSetionModel.h"
//#import "OneGoodsModel.h"

#import "GoodDetailController.h"

#import "OrderSureFirstVC.h"

#import "GoodsSkuListModel.h"
@interface ShopCarController ()
@property (nonatomic, weak) UIView *endView;

@property (nonatomic, weak) UIButton *selectAllBtn;

@property (nonatomic, weak) UILabel *allMoneyLabel;

@property (nonatomic, weak) UIButton *payButton;

/** <#note#> */
@property (nonatomic, weak) UIView *tableFooter;

/** <#note#> */
@property (nonatomic, weak) UIView *rootView;

/** qqq */

/** <#note#> */
@property (nonatomic, assign) NSInteger payCount;
@end

@implementation ShopCarController



- (UIView *)rootView{
    
    if (!_rootView) {
        
        UIView *view = [[UIView alloc]initWithFrame:self.view.bounds];
        
        view.backgroundColor = [UIColor whiteColor];
        _rootView = view;
        
        _rootView.hidden = YES;
        
//        UIImageView *imageView = [[UIImageView alloc]initWithFrame:CGRectMake(KScreenW * 0.65 * 0.5, (KScreenH - (KScreenW * 0.75)) / 2.0 , KScreenW * 0.35, KScreenW * 0.35)];
        
        UIImageView *imageView = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"cartNoContentIcon"]];
        
        imageView.center = CGPointMake(KScreenW * 0.5, KScreenH * 0.5);
        
        imageView.backgroundColor = [UIColor clearColor];
        
//        imageView.image = [UIImage imageNamed:@"cartNoContentIcon"];
        
        imageView.contentMode = UIViewContentModeScaleAspectFit;
        
        UILabel *topLabel = [[UILabel alloc]init];
        topLabel.text = @"购物车还是空的";
        topLabel.font = MYFONT(16);
        [topLabel sizeToFit];
        topLabel.centerX = imageView.centerX;
        topLabel.top = imageView.bottom + 10;
     
        
        [_rootView addSubview:imageView];
        [_rootView addSubview:topLabel];
        [self.view addSubview:_rootView];
        
    }
    
    
    return _rootView;
    
}

- (UIView *)endView{
    if (!_endView) {
        
        CGFloat tabbarH = IPhoneX ? 83 : 49;
        
         UIView *temp;
        
         if (self.type.length > 0) {
            temp = [[UIView alloc] initWithFrame:CGRectMake(0,KScreenH - tabbarH , KScreenW, tabbarH)];
        } else {
            temp = [[UIView alloc] initWithFrame:CGRectMake(0,KScreenH - (49 + tabbarH) , KScreenW, 49)];
        }
        _endView = temp;
        
   
        _endView.hidden = myShopCar.shopCarList.count > 0 ? NO : YES;


        [self.view addSubview:_endView];
        
        UIView *line = [[UIView alloc]initWithFrame:CGRectMake(0, 0, KScreenW, 0.5)];
        line.backgroundColor = colorWith(200, 200, 200);
        [_endView addSubview:line];
        
        UIButton *selectAllBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [_endView addSubview:selectAllBtn];
        [selectAllBtn setImage:IMG(@"shopcat_no_select") forState:UIControlStateNormal];
        [selectAllBtn setImage:IMG(@"shopcat_select") forState:UIControlStateSelected];
        selectAllBtn.imageEdgeInsets = UIEdgeInsetsMake(10, 10, 10, 10);
        [selectAllBtn addTarget:self action:@selector(selectAllProductAction:) forControlEvents:UIControlEventTouchUpInside];
        selectAllBtn.frame = CGRectMake(10, 0, 40, 40);
        selectAllBtn.centerY = 49 * 0.5;
        self.selectAllBtn = selectAllBtn;
        
        
        UILabel *allselectLabel = [[UILabel alloc] init];
        [_endView addSubview:allselectLabel];
        allselectLabel.text = @"全选";
        allselectLabel.font = [UIFont systemFontOfSize:14];
        allselectLabel.frame = CGRectMake(50, 0, 40, 40);
        allselectLabel.centerY = 49 * 0.5;
        
        
        
        UIButton *tempBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        self.payButton = tempBtn;
        [_endView addSubview:self.payButton];
        self.payButton.backgroundColor = themeColor;
        [self.payButton setTitle:@"付款(0)" forState:UIControlStateNormal];
        [self.payButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [self.payButton addTarget:self action:@selector(gotoOderPage) forControlEvents:UIControlEventTouchUpInside];
        self.payButton.titleLabel.font = [UIFont systemFontOfSize:14];
        self.payButton.frame = CGRectMake(KScreenW - 80, 0, 80, 49);
        
        if (self.type.length > 0  && IPhoneX) {
            
            UIButton *lastBtn = [UIButton buttonWithType:UIButtonTypeCustom];
            lastBtn.frame = CGRectMake(KScreenW - 80, 49, 80, 34);
            lastBtn.backgroundColor = [UIColor colorWithRed:65.0/255 green:164.0/255 blue:249.0/255 alpha:1];
            [lastBtn addTarget:self action:@selector(gotoOderPage) forControlEvents:UIControlEventTouchUpInside];
             [_endView addSubview:lastBtn];

        }
        
        
        
        
        UILabel *temp2 = [[UILabel alloc] init];
        self.allMoneyLabel = temp2;
        [_endView addSubview:self.allMoneyLabel];
        self.allMoneyLabel.text = @"合计：0.00P";
        self.allMoneyLabel.font = [UIFont systemFontOfSize:14];
        self.allMoneyLabel.textColor  = [UIColor blackColor];
        [self.allMoneyLabel sizeToFit];
        self.allMoneyLabel.right = self.payButton.left - 10;
        self.allMoneyLabel.centerY = self.payButton.centerY;
    }
    
    
    
    return _endView;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
//    self.view.backgroundColor =
//    self.plainTableView.rowHeight = UITableViewAutomaticDimension;
//    self.plainTableView.estimatedRowHeight = 100;
    
    [self.plainTableView registerNib:[UINib nibWithNibName:NSStringFromClass([ShopCarGoodsCell class]) bundle:nil] forCellReuseIdentifier:[ShopCarGoodsCell identifierStr]];
    
     [self.plainTableView registerNib:[UINib nibWithNibName:NSStringFromClass([ShopCarNothingCell class]) bundle:nil] forCellReuseIdentifier:[ShopCarNothingCell identifierStr]];
    
    [self.plainTableView registerNib:[UINib nibWithNibName:NSStringFromClass([ShopCarOHeaderView class]) bundle:nil] forHeaderFooterViewReuseIdentifier:[ShopCarOHeaderView identifierStr]];
    
    
    [self.plainTableView registerNib:[UINib nibWithNibName:NSStringFromClass([ShopCarTHeaderView class]) bundle:nil] forHeaderFooterViewReuseIdentifier:[ShopCarTHeaderView identifierStr]];
    
    [self.plainTableView registerNib:[UINib nibWithNibName:NSStringFromClass([RecommendGoodsCell class]) bundle:nil] forCellReuseIdentifier:[RecommendGoodsCell identifierStr]];
    
    
    if (self.type.length > 0) {
        
        CGFloat tableFooterH = myShopCar.shopCarList.count > 0 ? 49 : 0;
        UIView *tableFooter = [[UIView alloc]initWithFrame:CGRectMake(0, 0, KScreenW, tableFooterH)];
        tableFooter.backgroundColor = [UIColor whiteColor];
        self.tableFooter = tableFooter;
        self.plainTableView.tableFooterView = tableFooter;
        
    } else {
        
        CGFloat tableFooterH = myShopCar.shopCarList.count > 0 ? 49 : 0;
        UIView *tableFooter = [[UIView alloc]initWithFrame:CGRectMake(0, 0, KScreenW, tableFooterH)];
        tableFooter.backgroundColor = [UIColor whiteColor];
        self.tableFooter = tableFooter;
        self.plainTableView.tableFooterView = tableFooter;
    }
   
    // 设置标题
    if (@available(iOS 11.0, *)) {
//        
//        self.navigationController.navigationBar.prefersLargeTitles = YES;
//        self.navigationItem.largeTitleDisplayMode =  UINavigationItemLargeTitleDisplayModeAlways;
        
    }
    
    self.endView.backgroundColor = [UIColor whiteColor];
    
    
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(didClearShopCar) name:@"didClearShopCar" object:nil];

    
}
- (void)didClearShopCar{
    
    [self calculateTotalPrice];
    
    [self.plainTableView reloadData];
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self calculateTotalPrice];
    [self.plainTableView reloadData];
}


- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
//    return 1;
    
    if (myViewModel.tuiJianGoods.count > 0) {
        
        if (myShopCar.shopCarList.count > 0) {
            
            return myShopCar.shopCarList.count + 1;
            
            
        }else{
            
            return 2;
            
        }
        
        
    }else{
        
        if (myShopCar.shopCarList.count > 0) {
            
            
           return myShopCar.shopCarList.count;
            
        }else{
            
            return 0;
        }
        
        
    }
    
    
    
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    if (myViewModel.tuiJianGoods.count > 0) {
        
        if (myShopCar.shopCarList.count > 0) {
            
            if (section == myShopCar.shopCarList.count) {
                return 1;
            } else {
                return myShopCar.shopCarList[section].goods.count;
            }
            
            
        } else {
            
            if (section == 0) {
                return 1;
            } else {
                
                return 1;
                
            }
            
            
        }
        
    }else{
        
        if (myShopCar.shopCarList.count > 0) {
            
            
            return myShopCar.shopCarList[section].goods.count;
            
        }else{
            
            return 0;
            
        }
        
        
    }
    
  
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    
    UITableViewCell *cell;
    
    
    if (myViewModel.tuiJianGoods.count > 0) {
        
        if (myShopCar.shopCarList.count > 0) {
            
            if (indexPath.section == myShopCar.shopCarList.count) {
                
                cell = [tableView dequeueReusableCellWithIdentifier:[RecommendGoodsCell identifierStr]];
                RecommendGoodsCell *tempCell = (RecommendGoodsCell *)cell;
                tempCell.models = myViewModel.tuiJianGoods;
                return tempCell;
                
            } else {
                
                cell = [tableView dequeueReusableCellWithIdentifier:[ShopCarGoodsCell identifierStr]];
                
                ShopCarGoodsCell *tempCell = (ShopCarGoodsCell *)cell;
    
                tempCell.index = indexPath;
                
                tempCell.model = myShopCar.shopCarList[indexPath.section].goods[indexPath.row];
                
                return tempCell;
                
            }
            
            
            
        } else {
            
            if (indexPath.section == 0) {
                
                cell = [tableView dequeueReusableCellWithIdentifier:[ShopCarNothingCell identifierStr]];
                ShopCarNothingCell *tempCell = (ShopCarNothingCell *)cell;
                return tempCell;
                
            } else {
                
                cell = [tableView dequeueReusableCellWithIdentifier:[RecommendGoodsCell identifierStr]];
                
                RecommendGoodsCell *tempCell = (RecommendGoodsCell *)cell;
                
                tempCell.models = myViewModel.tuiJianGoods;
    
                
                return tempCell;
                
                
            }
            
            
        }
        
    }else{
        
        if (myShopCar.shopCarList.count > 0) {
            
            
            cell = [tableView dequeueReusableCellWithIdentifier:[ShopCarGoodsCell identifierStr]];
            
            ShopCarGoodsCell *tempCell = (ShopCarGoodsCell *)cell;

            
            tempCell.model = myShopCar.shopCarList[indexPath.section].goods[indexPath.row];

            
            tempCell.index = indexPath;
            
            
            return tempCell;
            
            
        }else{
            
            return [[UITableViewCell alloc]init];
            
        }
        
        
    }

    
    
    

}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (myViewModel.tuiJianGoods.count > 0) {
        
        if (myShopCar.shopCarList.count > 0) {
            
            if (indexPath.section == myShopCar.shopCarList.count) {
                
                if (myViewModel.tuiJianGoods.count % 2 == 0) {
                    
                    return (RecomGoodsLayoutH * (myViewModel.tuiJianGoods.count/2)) + (((myViewModel.tuiJianGoods.count/2) - 1) * 8);

                } else {
                    
                    return (RecomGoodsLayoutH * ((myViewModel.tuiJianGoods.count + 1)/2)) + ((((myViewModel.tuiJianGoods.count + 1)/2) - 1) * 8);

                }
              
                
            } else {
                
     
                
                return 92;
                
            }
            
            
            
        } else {
            
            if (indexPath.section == 0) {
                
                return 56;
                
            } else {
            
                
                
                if (myViewModel.tuiJianGoods.count % 2 == 0) {
                    
                    return (RecomGoodsLayoutH * (myViewModel.tuiJianGoods.count/2)) + (((myViewModel.tuiJianGoods.count/2) - 1) * 8);
                    
                } else {
                    
                    return (RecomGoodsLayoutH * ((myViewModel.tuiJianGoods.count + 1)/2)) + ((((myViewModel.tuiJianGoods.count + 1)/2) - 1) * 8);

                    
                }
                
                
            }
            
            
        }
        
    }else{
        
        if (myShopCar.shopCarList.count > 0) {
            
            
               return 92;
            
            
        }else{
            
            return 0;
            
        }
        
        
    }
    
    
    
    
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    
    return 0.00001;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    
    if (myViewModel.tuiJianGoods.count > 0) {
        
        if (myShopCar.shopCarList.count > 0) {
            
            return 44;
            
        } else {
            
            if (section == 0) {
                return 0.00001;
            } else {
                
                return 44;
                
            }
            
            
        }
        
    }else{
        
        if (myShopCar.shopCarList.count > 0) {
            
            
            return 44;
            
        }else{
            
            return 0.00001;
            
        }
        
        
    }
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    
    return nil;
}


- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    
    if (myViewModel.tuiJianGoods.count > 0) {
        
        if (myShopCar.shopCarList.count > 0) {
            
            if (section == myShopCar.shopCarList.count) {
                
                ShopCarTHeaderView *view = (ShopCarTHeaderView *)[tableView dequeueReusableHeaderFooterViewWithIdentifier:[ShopCarTHeaderView identifierStr]];
                
                return view;
                
            } else {
                
                ShopCarOHeaderView *view = (ShopCarOHeaderView *)[tableView dequeueReusableHeaderFooterViewWithIdentifier:[ShopCarOHeaderView identifierStr]];
                
                view.model = myShopCar.shopCarList[section];
                
                view.setion = section;
                
                
                return view;
                
            }
            
        } else {
            
            if (section == 0) {
                return [[UIView alloc]init];
            } else {
                
                ShopCarTHeaderView *view = (ShopCarTHeaderView *)[tableView dequeueReusableHeaderFooterViewWithIdentifier:[ShopCarTHeaderView identifierStr]];
                
                
                
                return view;
                
            }
            
            
        }
        
    }else{
        
        if (myShopCar.shopCarList.count > 0) {
            
            
            ShopCarOHeaderView *view = (ShopCarOHeaderView *)[tableView dequeueReusableHeaderFooterViewWithIdentifier:[ShopCarOHeaderView identifierStr]];
            
            view.model = myShopCar.shopCarList[section];
            
            view.setion = section;
            
            return view;
            
        }else{
            
            return [[UIView alloc]init];
            
        }
        
        
    }


}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    
    if (myViewModel.shopCar.shopCarList.count > 0) {
        
        if (indexPath.section == 0) {
            
            GoodDetailController *tempVC = [[GoodDetailController alloc]init];
            
            
            GoodsSkuListModel *model = myShopCar.shopCarList[indexPath.section].goods[indexPath.row];

            OneGoodsModel *tempModel = [[OneGoodsModel alloc]init];
            
            tempModel.goods_id = model.goods_id;
            
            tempModel.goods_image_url = model.goods_image_url;
            
            
            tempVC.goodsModel = tempModel;
            
            [self.navigationController pushViewController:tempVC animated:YES];
            
        }
    }
    
    
    
    
}


- (void)selectAllProductAction:(UIButton *)bt {
    
    bt.selected = !bt.selected;
    
    BOOL btselected = bt.selected;
    
    NSString *checked = @"";
    if (btselected) {
        checked = @"1";
    }
    else
    {
        checked = @"0";
    }
    
    for (GoodsSetionModel *setionModel in myShopCar.shopCarList) {
        setionModel.checked = checked;
        for (OneGoodsModel *subModel in setionModel.goods) {
            subModel.isSelect = checked;
        }
    }
    
    [self calculateTotalPrice];
    
    [self.plainTableView reloadData];
    
}


- (void)didClickSectionBtn:(UIButton *)btn withSection:(NSInteger)section{
    
    btn.selected = !btn.selected;
    
    GoodsSetionModel *model = myShopCar.shopCarList[section];
    
    if (btn.selected) {
        for (GoodsSkuListModel *subModel in model.goods) {
            subModel.isSelect = @"1";
        }
    } else {
        for (GoodsSkuListModel *subModel in model.goods) {
            subModel.isSelect = @"0";
            
        }
    }
    
    
    [self calculateTotalPrice];
    
    NSIndexSet *indexSet=[[NSIndexSet alloc]initWithIndex:section];
    
    [self.plainTableView reloadSections:indexSet withRowAnimation:UITableViewRowAnimationNone];
}



- (void)deleBtnDidClickWithIndexPath:(NSIndexPath *)index{
    
    UIAlertController *contr = [UIAlertController alertControllerWithTitle:nil message:@"确定删除此商品吗?" preferredStyle:UIAlertControllerStyleAlert];
    
    MJWeakSelf;
    UIAlertAction *action1 = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
        
        GoodsSetionModel *setionModel = myShopCar.shopCarList[index.section];
        
        [setionModel.goods removeObjectAtIndex:index.row];
        
        if (setionModel.goods.count < 1) {
            
            [myShopCar.shopCarList removeObjectAtIndex:index.section];
            
        }
        
        
        [weakSelf calculateTotalPrice];
        
        
        [weakSelf.plainTableView reloadData];

        
    }];
    
    
    UIAlertAction *action2 = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
        
    }];
    
    
    [contr addAction:action2];
    [contr addAction:action1];
    
    [self presentViewController:contr animated:YES completion:nil];
    
    
    
}



- (void)calculateTotalPrice{
    
    float num = 0.00;
    NSInteger payCount = 0;
    BOOL needSelect = YES;
    
    
    for (GoodsSetionModel *setionModel in myShopCar.shopCarList) {
        
        setionModel.checked = @"1";
        
        for (GoodsSkuListModel *subModel in setionModel.goods) {
            
            NSInteger count = [subModel.count integerValue];
            float sale = [subModel.price floatValue];
            if ([subModel.isSelect isEqualToString:@"1"]) {
                
                num = count*sale+ num;
                
                payCount = payCount + count;
                
            }else{
                
                setionModel.checked = @"0";
                
                if ( needSelect == YES) {
                    
                    needSelect = NO;
                }
                
            }
        }
    }
    
    NSString *moneys = [NSString stringWithFormat:@"%.2fP",num];
    NSString *tempString = [@"合计：" stringByAppendingString:moneys];
    self.allMoneyLabel.attributedText = [self changeLabelColorOriginalString:tempString changeString:moneys];
    [self.allMoneyLabel sizeToFit];
    self.allMoneyLabel.right= self.payButton.left - 10;
    self.allMoneyLabel.centerY = self.payButton.centerY;
    
    [self.payButton setTitle:[NSString stringWithFormat:@"付款(%ld)",(long)payCount] forState:UIControlStateNormal];
    
    self.payCount = payCount;
    
    self.selectAllBtn.selected = needSelect;
    
    NSInteger goodsCount = myShopCar.shopCarList.count;
    
    self.endView.hidden =  goodsCount > 0 ? NO : YES;
    
    
    NSInteger totalGoodsCount = [self calculateTotalGoodsCounts];
    
    self.tableFooter.height = totalGoodsCount > 0 ? 49 : 0;
    
    if (!(myShopCar.shopCarList.count > 0) && !(myViewModel.tuiJianGoods.count > 0)) {
        self.rootView.hidden = NO;
        self.plainTableView.hidden = YES;
        
    } else {
        self.rootView.hidden = YES;
        self.plainTableView.hidden = NO;
    }

}


- (void)gotoOderPage{
    
    if (self.payCount > 0) {
        
        OrderSureFirstVC *orderVC = [[OrderSureFirstVC alloc]initWithStyle:UITableViewStyleGrouped];
        NSMutableString *strM = [NSMutableString string];
        for (GoodsSetionModel *sectionModel in myViewModel.shopCar.shopCarList) {
            
            for (GoodsSkuListModel *sub in sectionModel.goods) {
                
                if ([sub.isSelect isEqualToString:@"1"]) {
                    
                    [strM appendString:sub.sku_id];
                    [strM appendString:@":"];
                    [strM appendString:sub.count];
                    [strM appendString:@","];
                }
                
          
                
            }
        }
        
        NSString *lastStr = [strM substringToIndex:strM.length - 1];
        
        
        orderVC.goodsListStr = lastStr;
        
        
        
        [self.navigationController pushViewController:orderVC animated:YES];
        
    }else{
        
        
        [SVProgressHUD showInfoWithStatus:@"你还没有选择商品哦"];
        
        
    }
    


    
//    NSLog(@"去支付");
}



- (NSMutableAttributedString *)changeLabelColorOriginalString:(NSString *)originalString changeString:(NSString *)changeString {
    
    NSRange changeStringRange = [originalString rangeOfString:changeString];
    NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:originalString];
    [attributedString addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:changeStringRange];
    return attributedString;
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    
    
}



@end
